﻿#include <iostream>
#include "LogicSystem.h"
#include <csignal>
#include <thread>
#include <mutex>
#include "AsioIOServicePool.h"
#include "CServer.h"
#include "ConfigMgr.h"
#include "RedisMgr.h"
#include "ChatServiceImpl.h"


bool bstop = false;
std::condition_variable cond_quit;
std::mutex mutex_quit;


int main()
{
    auto& cfg = ConfigMgr::GetInstance();
    auto server_name = cfg["SelfServer"]["Name"];

    try {
        //初始化iocontext线程池
        auto pool = AsioIOServicePool::getInstance();
        RedisMgr::getInstance()->HSet(LOGIN_COUNT, server_name, "0");
        //设置服务器参数
        ServerBuilder builder;
        //设置网络参数
        std::string server_address(cfg["SelfServer"]["Host"] + ":" + cfg["SelfServer"]["RPCPort"]);
        builder.AddListeningPort(server_address,
            grpc::InsecureServerCredentials());
        ChatServiceImpl service;
        builder.RegisterService(&service);
        // 创建服务器
        std::unique_ptr<grpc::Server> server = builder.BuildAndStart();
        std::cout << "RPC Server listening on" <<server_address<< std::endl;
        //grpc服务在另一个线程中运行
        std::thread grpc_server_thread([&server]() {
            server->Wait();
            });


        boost::asio::io_context  io_context;
        boost::asio::signal_set signals(io_context, SIGINT, SIGTERM);
        signals.async_wait([&io_context, pool,&server](auto, auto) {
            io_context.stop();
            pool->Stop();
            server->Shutdown();
            });
        auto port_str = cfg["SelfServer"]["Port"];
        CServer s(io_context, atoi(port_str.c_str()));
        io_context.run();


        RedisMgr::getInstance()->HDel(LOGIN_COUNT, server_name);
        RedisMgr::getInstance()->Close();
        grpc_server_thread.join();

    }
    catch (std::exception& e) {
        std::cerr << "Exception: " << e.what() << endl;
    }

    return 0;
}

